﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

using GroundWater.Data;
using GroundWater.BusinessActions;
using AbnormalTable = GroundWater.Data.AbnormalDataSet.WaterlevelAbnormalDataTable;
using AbnormalRow = GroundWater.Data.AbnormalDataSet.WaterlevelAbnormalRow;


namespace GroundWater.waterlevel
{
    public partial class WaterlevelAbnormal : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SiteUtil.Validate(this, "水位异常检查");

            if (!this.IsPostBack)
            {
                txtStartDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtEndDate.Text = DateTime.Now.ToString("yyyy-MM-dd");

                string startDate = DateTime.Now.ToString("yyyy-MM-dd");
                string endDate = DateTime.Now.ToString("yyyy-MM-dd");


                this.laseWarning.Visible = true;
                this.allWarning.Visible = false;

                string difference = System.Configuration.ConfigurationManager.AppSettings["WarningDifference"];
                txtDifference.Text = difference;

                //AbnormalTable abnormal = GroundWater.BusinessActions.WaterlevelAbnormal.FetchByTimeSpan(startDate, endDate, Convert.ToDecimal(txtDifference.Text));
                //if (abnormal == null || abnormal.Rows.Count == 0)
                //{
                //    btnCheck_Click(null, EventArgs.Empty);
                //}
                //else
                //{
                //    gvWarning.DataSource = abnormal;
                //    gvWarning.DataBind();
                //}

                btnCheck_Click(null, EventArgs.Empty);
            }
        }

        protected void RowDataBound(object sender, GridViewRowEventArgs args)
        {
            GridView gridView = (GridView)sender;

            if (gridView.SortExpression.Length > 0)
            {
                int cellIndex = -1;
                foreach (DataControlField field in gridView.Columns)
                {
                    if (field.SortExpression == gridView.SortExpression)
                    {
                        cellIndex = gridView.Columns.IndexOf(field);
                        break;
                    }
                }

                if (cellIndex > -1)
                {
                    if (args.Row.RowType == DataControlRowType.Header)
                    {
                        //  this is a header row,
                        //  set the sort style
                        args.Row.Cells[cellIndex].CssClass +=
                            (gridView.SortDirection == SortDirection.Ascending
                            ? " sortasc" : " sortdesc");
                    }
                }
            }

            if (args.Row.Cells.Count > 8)
            {
                if (args.Row.RowType == DataControlRowType.DataRow)
                {
                    if (args.Row.RowIndex > -1)
                    {
                        if (args.Row.Cells[8].Controls.Count > 0)
                        {
                            LinkButton btnDelete = args.Row.Cells[8].Controls[0] as LinkButton;
                            if (btnDelete != null && btnDelete.Text == "删除")
                            {
                                btnDelete.OnClientClick = "return confirm('您是否确认删除此项？');";
                            }
                        }
                    }
                }
            }

            if (args.Row.Cells.Count > 6)
            {
                if (args.Row.RowType == DataControlRowType.DataRow)
                {
                    if (args.Row.RowIndex > -1)
                    {
                        if (args.Row.Cells[6].Controls.Count > 0)
                        {
                            Image image = args.Row.Cells[6].Controls[0] as Image;
                            if(image != null)
                            {
                                if (image.ImageUrl.ToLower() == "true")
                                {
                                    image.ImageUrl = @"~\images\arrow_up.png";
                                }
                                else
                                {
                                    image.ImageUrl = @"~\images\arrow_down1.gif";
                                }


                            }

                            //AbnormalRow rwo = (args.Row.DataItem as DataRowView).Row as AbnormalRow;
                            
                            //if (btnDelete != null && btnDelete.Text == "删除")
                            //{
                            //    btnDelete.OnClientClick = "return confirm('您是否确认删除此项？');";
                            //}
                        }
                    }
                }
            }


        }


        protected void btnQuery_Click(object sender, EventArgs e)
        {
            this.laseWarning.Visible = false;
            this.allWarning.Visible = true;
        }

        protected void btnCheck_Click(object sender, EventArgs e)
        {
            this.laseWarning.Visible = true;
            this.allWarning.Visible = false;

            #region validate
            //if (!Husb.Util.CommonUtil.IsInteger(txtDays.Text))
            //{
            //    return;
            //}
            if(!Husb.Util.CommonUtil.IsNumber(txtDifference.Text))
            {
                return;
            }
            //DateTime endDate = DateTime.Now.Date;
            //DateTime startDate = DateTime.Now.Date.AddDays(1 - Int32.Parse(txtDays.Text));
            if (txtStartDate.Text.Length < 6)
            {
                txtStartDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }
            if (txtEndDate.Text.Length < 6)
            {
                txtEndDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }

            DateTime endDate1;
            DateTime startDate1;
            

            if (!DateTime.TryParse(txtStartDate.Text, out startDate1) || !DateTime.TryParse(txtEndDate.Text, out endDate1))
            {
                return;
            }

            string startDate = txtStartDate.Text;
            string endDate = txtEndDate.Text;
            


            DataTable dt = Monitoring.FetchWaterLeveByDate(startDate, endDate);

            //DataTable dt = Monitoring.FetchWaterLeveByDate("2009-05-10", "2009-05-15");

            if (dt == null || dt.Rows.Count < 2)
            {
                return;
            }
            #endregion

            AbnormalDataSet abnormal = new AbnormalDataSet(); 

            string defalutDifference = System.Configuration.ConfigurationManager.AppSettings["WarningDifference"];
            decimal difference = Math.Abs( Convert.ToDecimal(txtDifference.Text));
            //if (difference < Convert.ToDecimal(defalutDifference))
            //{
            //    abnormal = new AbnormalDataSet();
            //    return;
            //}
            bool isInsert = difference >= Convert.ToDecimal(defalutDifference);
            
            int p = 1;
            int cnt = dt.Rows.Count;
            decimal current = (decimal)dt.Rows[0]["Waterlevel"];
            decimal previous = 0m;
            string wellCode = dt.Rows[0]["WellCode"].ToString();

            while (p < cnt)
            {
                #region while
                previous = (decimal)dt.Rows[p]["Waterlevel"];

                if (wellCode != dt.Rows[p]["WellCode"].ToString())
                {
                    current = (decimal)dt.Rows[p]["Waterlevel"];
                    wellCode = dt.Rows[p]["WellCode"].ToString();
                    p++;
                    continue;
                }

                if (Math.Abs( previous - current) >= difference)
                {
                    // record  WellName
                    InsertTempAbnormal(abnormal, 0 - p, wellCode, dt.Rows[p]["WellName"].ToString(), (DateTime)dt.Rows[p]["MonitorTime"], difference, previous, current);
                    if (isInsert)
                    {
                        //AbnormalRow row = GroundWater.BusinessActions.WaterlevelAbnormal.FetchByMonitoringId(wellCode, (DateTime)dt.Rows[p]["MonitorTime"], difference);
                        //if (row == null)
                        //{
                        //    InsertAbnormal(abnormal, wellCode, (DateTime)dt.Rows[p]["MonitorTime"], difference, previous, current);
                        //}
                    }
                }

                current = previous;
                p++;

                #endregion
            }

            //gvWarning.DataSource = GroundWater.BusinessActions.WaterlevelAbnormal.FetchByTimeSpan(startDate.ToString("yyyy-MM-dd"), endDate.ToString("yyyy-MM-dd"), HttpContext.Current.User.Identity.Name);

            if(abnormal.WaterlevelAbnormal.Rows.Count > 0)
            {
                gvWarning.DataSource = abnormal.WaterlevelAbnormal;
                gvWarning.DataBind();

                lblEmpty.Visible = false;
            }
            else
            {
                lblEmpty.Text = "<br />您所选定的时间段内，按告警差值为" + txtDifference.Text + "米来检查，无异常水位信息！";
                lblEmpty.Visible = true;
            }
            
            updPanel.Update();
        }

        private void InsertAbnormal(AbnormalDataSet tmpDataSet, string wellCode, DateTime monitoringDate, decimal difference, decimal previous, decimal current)
        {
            AbnormalDataSet abnormal = new AbnormalDataSet();
            AbnormalRow row = abnormal.WaterlevelAbnormal.NewWaterlevelAbnormalRow();

            row.Id = 1;// 这里是随便输入的一个值。
            row.PreviousWaterlevel = previous;
            row.CurrentWaterlevel = current;
            row.Difference = previous - current;
            row.WarningDifference = difference;

            row.ExamineDate = DateTime.Now;
            row.Examiner = HttpContext.Current.User.Identity.Name;
            row.MonitoringDate = monitoringDate;
            row.WellCode = wellCode;
            //row.MonitoringId

            abnormal.WaterlevelAbnormal.Rows.Add(row);

            //InsertTempAbnormal(tmpDataSet, wellCode, monitoringDate, difference, previous, current);


            GroundWater.BusinessActions.WaterlevelAbnormal.Update(abnormal, false, false,null);
        }

        private void InsertTempAbnormal(AbnormalDataSet tmpDataSet, int id, string wellCode, string wellName, DateTime monitoringDate, decimal difference, decimal previous, decimal current)
        {
            AbnormalRow tmp = tmpDataSet.WaterlevelAbnormal.NewWaterlevelAbnormalRow();
            tmp.Id = id;// 这里是随便输入的一个值。
            tmp.PreviousWaterlevel = previous;
            tmp.CurrentWaterlevel = current;
            tmp.Difference = Math.Abs( previous - current);
            tmp.WarningDifference = difference;
            tmp.IsRising = previous - current < 0;

            tmp.ExamineDate = DateTime.Now;
            tmp.Examiner = HttpContext.Current.User.Identity.Name;
            tmp.MonitoringDate = monitoringDate;
            tmp.WellCode = wellCode;
            tmp.WellName = wellName;



            tmpDataSet.WaterlevelAbnormal.Rows.Add(tmp);
        }

        protected void odsLastAbnormal_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            //if (!Husb.Util.CommonUtil.IsInteger(txtDays.Text))
            //{
            //    return;
            //}
            //if(!Husb.Util.CommonUtil.IsNumber(txtDifference.Text))
            //{
            //    return;
            //}
            //DateTime endDate = DateTime.Now.Date;
            //DateTime startDate = DateTime.Now.Date.AddDays(1 - Int32.Parse(txtDays.Text));
            //decimal difference = Convert.ToDecimal(txtDifference.Text) / 100;

            //e.InputParameters["startDate"] = startDate.ToString("yyyy-MM-dd");
            //e.InputParameters["endDate"] = endDate.ToString("yyyy-MM-dd");
            //e.InputParameters["warningDifference"] = difference;
        }


    }
}
